package simple.engine.objects;

import java.nio.ByteBuffer;
import java.nio.ByteOrder;
import java.nio.FloatBuffer;

import javax.microedition.khronos.opengles.GL10;

import simple.engine.common.SimpleUtils;
import android.graphics.Bitmap;
import android.graphics.Bitmap.Config;
import android.graphics.Canvas;
import android.graphics.Matrix;
import android.opengl.GLUtils;

public class Texture2D {

	private int[]  mTexture = new int[1];
	private FloatBuffer mTextureBuffer;
	
	public Texture2D(GL10 gl, Bitmap bitmap)
	{
		float mTextureCoords[] = {
			// Mapping coordinates for the vertices
			0.0f, 1.0f,		// top left		(V2)
			0.0f, 0.0f,		// bottom left	(V1)
			1.0f, 1.0f,		// top right	(V4)
			1.0f, 0.0f		// bottom right	(V3)
		};

		int width = bitmap.getWidth();
		int height = bitmap.getHeight();
		
		if(!SimpleUtils.isPowerOfTwo(width)) width = SimpleUtils.nextPowerOfTwo(width);
		if(!SimpleUtils.isPowerOfTwo(height)) height = SimpleUtils.nextPowerOfTwo(height);
		
		if(width != bitmap.getWidth() || height != bitmap.getHeight())
		{			
			Bitmap bmp = Bitmap.createBitmap(width, height, Config.ARGB_8888);
			Canvas c = new Canvas(bmp);

			mTextureCoords[1] = (float)bitmap.getHeight() / (float) height;
			mTextureCoords[5] = (float)bitmap.getHeight() / (float) height;
			
			mTextureCoords[4] = (float)bitmap.getWidth() / (float) width;
			mTextureCoords[6] = (float)bitmap.getWidth() / (float) width;
			
			c.drawBitmap(bitmap, new Matrix(), null);
			bitmap = bmp;
		}
		
		// generate one texture pointer and bind it to our array
		gl.glGenTextures(1, mTexture, 0);
		gl.glBindTexture(GL10.GL_TEXTURE_2D, mTexture[0]);
		
		// create nearest filtered texture
		gl.glTexParameterf(GL10.GL_TEXTURE_2D, GL10.GL_TEXTURE_MIN_FILTER, GL10.GL_NEAREST);
		gl.glTexParameterf(GL10.GL_TEXTURE_2D, GL10.GL_TEXTURE_MAG_FILTER, GL10.GL_LINEAR);

		// Use Android GLUtils to specify a two-dimensional texture image from our bitmap
		GLUtils.texImage2D(GL10.GL_TEXTURE_2D, 0, bitmap, 0);

		// Clean up
		bitmap.recycle();
		
		// Create texture buffer
		ByteBuffer byteBuffer = ByteBuffer.allocateDirect(8 * 4);
		byteBuffer.order(ByteOrder.nativeOrder());
		mTextureBuffer = byteBuffer.asFloatBuffer();
		mTextureBuffer.put(mTextureCoords);
		mTextureBuffer.position(0);
	}
	
	public int getTexturePointer()
	{
		return mTexture[0];
	}
	
	public FloatBuffer getTextureBuffer()
	{
		return mTextureBuffer;
	}
	
}
